package org.sxp.common.utils.datax.writer;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.sxp.common.utils.SpringContextUtils;
import org.sxp.modules.datasource.entity.DatabaseDO;
import org.sxp.modules.datasource.service.DatabaseService;
import org.sxp.modules.dataworks.dto.SyncDTO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * mysql writer构建类
 *
 * @author zhouhongfa@gz-yibo.com
 * @ClassName MysqlWriter
 * @Version 1.0
 * @since 2019/7/30 23:08
 */
public class MongoDbWriter extends BaseWriter implements IDataxWriter {
    public MongoDbWriter(SyncDTO syncDTO) {
        super(syncDTO);
    }

    @Override
    public String getName() {
        return "mongodbwriter";
    }

    @Override
    public Map<String, Object> build() {
        DatabaseService databaseService = SpringContextUtils.getBean(DatabaseService.class);
        DatabaseDO jobDatasource = databaseService.getById(syncDTO.getTargetDb());
        Map<String, Object> writerObj = Maps.newLinkedHashMap();
        writerObj.put("name", getName());

        Map<String, Object> parameterObj = Maps.newLinkedHashMap();
        parameterObj.put("address", StrUtil.split(jobDatasource.getUrl(), ","));
        parameterObj.put("userName", jobDatasource.getUsername());
        parameterObj.put("userPassword", jobDatasource.getPassword());
        parameterObj.put("dbName", jobDatasource.getDbName());
        parameterObj.put("collectionName", syncDTO.getTargetTable());

        parameterObj.put("column", syncDTO.getTargetField());
        if(StrUtil.isNotBlank(syncDTO.getWriteMode())){
            JSONObject writeMode = new JSONObject();
            writeMode.put("isReplace", true);
            writeMode.put("replaceKey", syncDTO.getWriteMode());
            parameterObj.put("writeMode", writeMode);
        }
        writerObj.put("parameter", parameterObj);
        return writerObj;
    }

    @Override
    protected void afterBackBuild() {

    }
}
